package com.onlygx.dva.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  链路追踪日志打印工具
 * </p>
 *
 * @author 高祥
 * @since 2023-05-16
 */
@Slf4j
public class OpenTelemetryLogUtils {

    public static String VERSION = "V2.x.x";

    public static String LEVEL_INFO = "INFO";
    public static String LEVEL_DEBUG = "DEBUG";
    public static String LEVEL_ERROR = "ERROR";

    /**
     * 展示info级别的日志
     */
    public static void showInfo(String traceParent,String message){

        log.info(JSONUtil.toJsonStr(showDefault(traceParent, message, LEVEL_INFO)));
    }

    /**
     * 展示error级别的日志
     */
    public static void showError(String traceParent,String message){

        log.error(JSONUtil.toJsonStr(showDefault(traceParent, message, LEVEL_ERROR)));
    }

    /**
     * 展示debug级别的日志
     */
    public static void showDebug(String traceParent,String message){

        log.debug(JSONUtil.toJsonStr(showDefault(traceParent, message, LEVEL_DEBUG)));
    }


    private static Map<String,String> showDefault(String traceParent, String message, String levelInfo) {
        Map<String,String> logMap = new HashMap<>();
        logMap.put("timestamp", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        logMap.put("type","请求日志");
        logMap.put("version",VERSION);
        logMap.put("level", levelInfo);
        logMap.put("message",message);
        try {
            if(StrUtil.isNotEmpty(traceParent)){
                String[] params = traceParent.split("-");
                logMap.put("traceID",params[1]);
                logMap.put("spanID",params[2]);
            }
        } catch (Exception e) {
            log.error("未在header中检测到追踪信息。");
        }
        return logMap;
    }

}
